<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Frontend_User extends Controller_Frontend {
	
	public function action_profile()
	{
		$view = new View('frontend/user.profile');
		
		// avatar
		if (isset($_POST['user']['photo']['submit']))
		{
			$error = FALSE;
			
			if ( ! empty($_POST['user']['photo']['url']) AND ! Valid::url($_POST['user']['photo']['url']))
				$error = 'Адрес изображения указан неверно.';
			
			if ($error === FALSE AND ! empty($_POST['user']['photo']['url']))
			{
				$getimagesize = @getimagesize($_POST['user']['photo']['url']);

				if ( ! isset($getimagesize[0]))
					$error = 'Не удалось получить информацию об изображении '.$_POST['user']['photo']['url'].'.';
				elseif ( ! in_array($getimagesize['mime'], array('image/jpeg', 'image/jpg', 'image/png', 'image/gif')))
					$error = 'Допустимые форматы изображения: JPEG, PNG и GIF.';
				elseif ($getimagesize[0] > 150 OR $getimagesize[1] > 150)
					$error = 'Максимальный размер изображения 150×150 точек.';
			}
			
			if ($error === FALSE)
			{
				$user = Model_Reg::get('user');
				$user->photo = $_POST['user']['photo']['url'];
				$user->save();
				
				Request::current()->redirect(Request::current()->url());
			}
			
			$view->error = $error;
		}
		
		// main
		if (isset($_POST['user']['main']['submit']))
		{
			$error = FALSE;
			
			$nickname = isset($_POST['user']['main']['nickname'])
				? trim(strip_tags($_POST['user']['main']['nickname']))
				: FALSE;
			
			$first_name = trim(strip_tags($_POST['user']['main']['first_name']));
			$last_name = trim(strip_tags($_POST['user']['main']['last_name']));
			$country = trim(strip_tags($_POST['user']['main']['country']));
			$city = trim(strip_tags($_POST['user']['main']['city']));
			
			if ( ! empty($nickname))
			{
				$exist = ORM::factory('User')->where('nickname', '=', $nickname)->where('id', '!=', Model_Reg::get('user')->id)->find();

				if (isset($exist->id))
					$error = 'Ник '.$exist.' занят.';
				elseif (preg_match('/^Пользователь \#{d+}$/', $nickname) AND Model_User::nickname(Model_Reg::get('user')) != $nickname)
					$error = 'Ник '.$nickname.' является системным, введите другой.';
			}
			
			if ($error === FALSE)
			{
				if (Model_User::nickname(Model_Reg::get('user')) == $nickname)
					$nickname = '';
				
				$user = Model_Reg::get('user');
				if ($nickname !== FALSE) $user->nickname = $nickname;
				$user->first_name = $first_name;
				$user->last_name = $last_name;
				$user->country = $country;
				$user->city = $city;
				$user->save();
				
				Request::current()->redirect(Request::current()->url());
			}
			
			$view->error = $error;
		}
		
		//contacts
		if (isset($_POST['user']['contacts']['submit']))
		{
			$error = FALSE;
			
			$email = trim(strip_tags($_POST['user']['contacts']['email']));
			
			if ( ! empty($email) AND ! Valid::email($email))
				$error = 'E-mail указан неверно.';
			
			if ($error === FALSE AND ! empty($email) AND Model_Reg::get('user')->email != $email)
			{
				$user = Model_Reg::get('user');
				$user->email_new = $email;
				$user->save();
				
				Model_Email_User::send_confirm_link_for_email($user);
				
				Request::current()->redirect(Request::current()->url());
			}
			elseif ($error === FALSE AND empty($email))
			{
				$user = Model_Reg::get('user');
				$user->email = NULL;
				$user->email_new = NULL;
				$user->save();
				
				Request::current()->redirect(Request::current()->url());
			}
			
			$view->error = $error;
		}
		
		$this->template->content = $view;
	}
	
	public function action_logout()
	{
		Cookie::delete('uIdentity');
		Request::current()->redirect('/');
	}
	
	public function action_confirm()
	{
		$view = new View('frontend/user.confirm.success');
		
		$user_id = Request::current()->param('user_id');
		$hash = Request::current()->param('hash');
		$timelimit = Request::current()->param('timelimit');
		
		$user = ORM::factory('User')->where('id', '=', $user_id)->find();
		
		if ( ! isset($user->id))
			throw new HTTP_Exception_404;
		
		if ( ! Model_Email_User::check_confirm_code($user, $timelimit, $hash))
			throw new HTTP_Exception_404;
		
		if ($user->id != Model_Reg::get('user')->id)
			throw new HTTP_Exception_404;
		
		$user->email = $user->email_new;
		$user->email_new = NULL;
		$user->save();
		
		$view->user = $user;
		
		$this->template->content = $view;
	}
	
}